package com.javen.controller;



import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.javen.common.ParamCode;
import com.javen.common.Response;
import com.javen.model.Banner;

import com.javen.service.BannerService;


@Controller  
@RequestMapping("/banner") 
public class BaanerController {
private static Logger log=LoggerFactory.getLogger(BaanerController.class);
	
	@Autowired
	private BannerService bannservice;
	
	Banner ban = new Banner();
	
	@RequestMapping("/springUpload")
	  public @ResponseBody Response springUpload(HttpServletRequest req ,@RequestParam("file") CommonsMultipartFile file) 
	    {     
		     
		  Response res = new Response();
		 
	        System.out.println("fileName："+file.getOriginalFilename());
	        String path=req.getServletContext().getRealPath("/uploadFile")+new Date().getTime()+file.getOriginalFilename();
	         
	        File newFile=new File(path);
	        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	        try {
				file.transferTo(newFile);
				ban.setPicUrl(path);
				res.setRespone(ParamCode.SUCSESS);
				res.setMsg("图片上传成功");
				return res;
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				res.setRespone(ParamCode.FAIL);
				res.setMsg("图片上传失败");
				return res;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				res.setRespone(ParamCode.FAIL);
				res.setMsg("图片上传失败");
				return res;
			}
	      
	    }
	@RequestMapping(value="/bannerinsert",method=RequestMethod.GET)
	public @ResponseBody Response bannerInsernt(@RequestBody Banner banner,HttpServletRequest request,Model model) {
		Response res = new Response();
		
		if(null==banner) {
			 res.setRespone(ParamCode.PARAMERROR);
             res.setMsg("上传参数错误");
             return res;
		}
		if(null==ban.getPicUrl()) {
			 res.setRespone(ParamCode.FAIL);
             res.setMsg("图片上传失败");
             return res;
		}
		banner.setPicUrl(ban.getPicUrl());
		banner.setDate(new Date());
		log.info("banner的数据："+banner.toString());
		int i =bannservice.inserntBanner(banner);
		if(i>0) {
			res.setRespone(ParamCode.SUCSESS);
			res.setMsg("banner上传成功");
		}else {
			res.setRespone(ParamCode.FAIL);
			res.setMsg("banner上传失败");	
		}
		return res;
	}

}
